package com.llyb.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.llyb.entities.User;
import com.llyb.properties.PatternProperties;
import com.llyb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@RefreshScope // 热更新配置
@RestController
@RequestMapping(value = "/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 通过反射
    @Value("${server.port}")
    String port;

    @Value("${datetime.format}")
    String format;

    @Autowired
    private PatternProperties patternProperties;

    @SentinelResource("hotKey")
    @GetMapping(value = "/findUserByUserId/{userId}")
    public User findUserByUserId(@PathVariable(value = "userId") Long userId,
                                    @RequestHeader(name = "router-token",required = false) String routerToken,
                                 @RequestHeader(name = "default-token",required = false) String defaultToken
    ) throws InterruptedException {
        User user = userService.findUserByUserId(userId);
        user.setAddress(user.getAddress()+"-"+port);

        /*// 测试异步请求使用
        Thread.sleep(10000);*/


        System.out.println(routerToken);
        System.out.println(defaultToken);

        /*System.out.println(format);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(patternProperties.getFormat());
        String dateTime = simpleDateFormat.format(new Date());
        System.out.println(dateTime);*/
        return user;
    }


    // 修改用户数据端点   (流量控制的关联模式)
    @GetMapping(value = "/updateUserById")
    public String updateUserById() {
        return "修改用户数据成功";
    }

    @GetMapping(value = "/save")
    public String save() {
        userService.queryUsers();
        System.out.println("保存用户");
        return "订单保存成功" ;
    }

    @GetMapping(value = "/query")
    public String query() {
        userService.queryUsers();
        System.out.println("查询用户");
        return "查询用户成功" ;
    }

}